package com.financing.platform.task;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.financing.platform.SMSDict;
import com.financing.platform.dao.IJpushMessageDao;
import com.financing.platform.dto.MessageJpushDTO;
import com.financing.platform.dto.PhonePushDTO;
import com.financing.platform.service.IJPushService;
import com.financing.platform.util.Dict;
import com.financing.platform.util.StringUtil;

/**
 * 极光推送消息下发
 * 
 * @author qiye
 *
 */
@Component(value = "messageJpushSendJob")
public class MessageJpushSendJob {

	private static boolean runTimeFlag = false;

	Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private IJpushMessageDao jpushMessageDao;

	@Autowired
	private IJPushService jPushService;

	@Scheduled(cron = "0/10 * * * * ?")
	public void sendMessageJob() {
		if (runTimeFlag) {
			return;
		} else {
			runTimeFlag = true;
		}
		MessageJpushDTO messageJpushDTO = new MessageJpushDTO();
		log.info("Jpush Messageproducer begin run");

		messageJpushDTO.setFpJpushSendTime(null);
		messageJpushDTO.setFpJpushSendType(Dict.message_type_now);
		messageJpushDTO.setFpJpushSendStatus(Dict.message_status_not_send);
		messageJpushDTO.setFpJpushSendTimes(Dict.message_max_send_times);
		messageJpushDTO.setPageNo(1);
		messageJpushDTO.setPageSize(200);
		messageJpushDTO.setUpdateBy("system");
		messageJpushDTO.setUpdateDate(new Date());
		//设置为查询独立店铺
//		messageJpushDTO.setFpJpushSource("shop");
		
		// 实时推送
		List<MessageJpushDTO> messageList = jpushMessageDao.queryJpushMessageListForJob(messageJpushDTO);
		while (null != messageList && !messageList.isEmpty()) {
			for (MessageJpushDTO message : messageList) {
				try {
					message.setFpJpushSendStatus(Dict.message_send_status_sending);
					jpushMessageDao.updateJpushMessage(message);
					messageSend(message);
				} catch (SQLException e) {
					log.warn("update Message status error:", e);
				}
			}

			messageList = jpushMessageDao.queryJpushMessageListForJob(messageJpushDTO);
		}

		// 定时推送
		messageJpushDTO.setFpJpushSendType(Dict.message_type_after);
		messageJpushDTO.setFpJpushSendTime(new Date());
		messageList = jpushMessageDao.queryJpushMessageListForJob(messageJpushDTO);
		for (MessageJpushDTO message : messageList) {
			message.setFpJpushSendStatus(Dict.message_send_status_sending);
			try {
				jpushMessageDao.updateJpushMessage(message);
				messageSend(message);
			} catch (SQLException e) {
				log.warn("update Message status error:", e);
			}
		}
		runTimeFlag = false;
		log.info("Jpush Messageproducer end run");
	}

	/**
	 * 
	 * @Title: messageSend @Description: 推送极光消息 @param message @return
	 * void @throws
	 */
	private void messageSend(MessageJpushDTO message) {

		PhonePushDTO dto = new PhonePushDTO();

		Map<String, String> extraMap = new HashMap<String, String>();
		extraMap.put("redirct", message.getFpJpushRedrict());
		extraMap.put("msgtype", message.getFpJpushMsgType());

		List<String> aliasesList = new ArrayList<String>();
		if (!StringUtil.isNullOrEmptyStr(message.getFpJpushMsgRec())) {
			aliasesList.add(message.getFpJpushMsgRec());
		}
		dto.setAliseList(aliasesList);
		dto.setContent(message.getFpJpushContent());
		dto.setTitle(message.getFpJpushTitle());
		dto.setExtraMap(extraMap);
		dto.setJpushSource(message.getFpJpushSource());  //选择类型
		try {

			Map<String, Object> result = jPushService.pushAllPhone(dto);

			// 如果设备不在线，则不推送
			if ((null != result.get("isOnline")) && !(Boolean) result.get("isOnline")) {
				message.setFpJpushSendStatus(Dict.message_status_not_send);
				message.setFpJpushSendTimes(null);
			}
			if (Dict.sms_send_success.equals(result.get(SMSDict.result))) {
				message.setFpJpushMsgId(result.get("msg_id").toString());
				message.setFpJpushMsgSendNo(result.get("sendNo").toString());
				message.setFpJpushSendStatus(Dict.message_send_status_success);
				message.setFpJpushSendTime(new Date());
			} else if (Dict.sms_send_fail.equals(result.get(SMSDict.result))) {
				message.setFpJpushSendStatus(Dict.message_send_status_fail);
				message.setFpJpushSendTime(new Date());
			}
		} catch (Exception e) {
			log.error("send jpush error!", e);
			message.setFpJpushSendTime(new Date());
			message.setFpJpushSendStatus(Dict.message_send_status_fail);
		}

		try {
			if (null == message.getFpJpushSendTimes()) {
				message.setFpJpushSendTimes(1);
			} else {
				message.setFpJpushSendTimes(message.getFpJpushSendTimes() + 1);
			}
			message.setFpJpushSendTime(new Date());
			jpushMessageDao.updateJpushMessage(message);
		} catch (SQLException e) {
			log.warn("update message error!", e);
		}
	}

}
